package utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

@Slf4j
public class ApacheHttpUitls {
    public static boolean getStreamGetResponse(String url, String requestBody, String outputFilePath) throws Exception {
        InputStream inputStream = null;
        OutputStream outputStream = null;
        CloseableHttpResponse response = null;
        try{

            //创建httpclient对象
            CloseableHttpClient client = HttpClients.createDefault();
            HttpGetWithEntity httpGetWithEntity = new HttpGetWithEntity(url);
            HttpEntity httpEntity = new StringEntity(requestBody, ContentType.APPLICATION_JSON);
            httpGetWithEntity.setEntity(httpEntity);
            //执行请求操作，并拿到结果（同步阻塞）
            response = client.execute(httpGetWithEntity);
            //获取结果实体
            HttpEntity entity = response.getEntity();
            log.info("requestUrl: {}, requestBody: {}", url, requestBody);
            if (entity != null) {

                inputStream = entity.getContent();
                Path path = Paths.get(outputFilePath);
                if (!Files.exists(path)) {
                    try {
                        Files.createFile(path);
                    } catch (IOException e) {
                        log.error("File create error ", e);
                        // 处理异常，例如输出错误消息或退出程序
                    }
                }
                outputStream = Files.newOutputStream(path);

                byte[] buffer = new byte[1024]; // 可以根据需要调整缓冲区大小
                int bytesRead;
                while ((bytesRead = inputStream.read(buffer)) != -1) {
                    outputStream.write(buffer, 0, bytesRead);
                }
                log.info("File downloaded and saved at " + outputFilePath);
            }else{
                log.error("Http get Entity is null");
                return false;
            }
            return true;
        } catch (Exception e){
            log.error("File download error ", e);
            return false;
        } finally {
            //释放链接
            if (response != null) response.close();
            if (inputStream != null) inputStream.close();
            if (outputStream != null) outputStream.close();
        }
    }

}

